package tk.heimashuma.store.web.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import tk.heimashuma.store.config.AlipayProperties;
import tk.heimashuma.store.entity.Transaction;
import tk.heimashuma.store.exception.OrderNullException;
import tk.heimashuma.store.service.PayService;
import tk.heimashuma.store.utils.IpConfiguration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Optional;
import java.util.UUID;

@Controller
@RequestMapping("/alipay/page")
public class AlipayPagePayController {

    @Autowired
    private AlipayProperties alipayProperties;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private AlipayController alipayController;
    @Autowired
    private PayService payService;
    @PostMapping("/gotoPayPage")
    public void gotoPayPage(String tId, HttpServletResponse response) throws AlipayApiException, IOException, OrderNullException {
        // 查询
        Transaction transaction = payService.findTranSaction(tId);
        if(!Optional.ofNullable(transaction).isPresent()){
            throw new OrderNullException("订单不存在");
        }else if(transaction.getState() == 1){
            // 订单已经处理完成
            response.sendRedirect("/repetitionOrder");
            return;
        }

        // 订单模型
        String productCode = "FAST_INSTANT_TRADE_PAY";
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        String oid = UUID.randomUUID().toString();
        model.setOutTradeNo(tId);
        model.setSubject("黑马数码购物");
        model.setTotalAmount(String.valueOf(transaction.getTotalMoney()));
        model.setBody("黑马数码购物，共"+transaction.getTotalMoney()+"元");
        model.setProductCode(productCode);
        // 记录订单uid
        transaction.setState(3);
        payService.save(transaction);

        AlipayTradePagePayRequest pagePayRequest =new AlipayTradePagePayRequest();
        // 支付完成跳转的页面
        pagePayRequest.setReturnUrl("http://localhost:"+ IpConfiguration.getPort() +"/alipay/page/returnUrl");
        pagePayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
        pagePayRequest.setBizModel(model);

        // 调用SDK生成表单, 并直接将完整的表单html输出到页面
        String form = alipayClient.pageExecute(pagePayRequest).getBody();
        response.setContentType("text/html;charset=" + alipayProperties.getCharset());
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }

    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, AlipayApiException {
        response.setContentType("text/html;charset=" + alipayProperties.getCharset());

        boolean verifyResult = alipayController.rsaCheckV1(request);
        if(verifyResult){
            //验证成功
            //请在这里加上商户的业务逻辑程序代码，如保存支付宝交易号
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            payService.paySuccess(out_trade_no);
            return "redirect:/index";

        }else{
            return "pagePayFail";
        }
    }
}
